<?php
/**
 * Character model file.
 *
 * Infectamic: browser game (http://infectamic.goldzoneweb.info)
 * Copyright 2011, Loic Chardonnet
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 */

App::uses('PronounceableWord', 'Lib');

/**
 * Class for Character model.
 */
class Character extends AppModel {
    public $name = 'Character';

    var $_schema = array(
	'id' => array(
            'type' => 'integer',
            'length' => 20,
	),
	'name' => array(
            'type' => 'string',
            'length' => 20,
	),
	'resource_kept' => array(
            'type' => 'integer',
            'length' => 7,
	),
	'resource_spent' => array(
            'type' => 'integer',
	),
        'attack_modifier' => array(
            'type' => 'integer',
	),
        'defense_modifier' => array(
            'type' => 'integer',
	),
        'resource_modifier' => array(
            'type' => 'integer',
	),
        'created' => array(
            'type' => 'datetime',
	),
    );

    /**
     * Generates randomly a new Character.
     *
     * @return boolean True if a new character has been generated, or else false
     */
    public function generateRandomly() {
        $hasGenerated = false;
        $pronounceableWord = new PronounceableWord();
        $generatedName = $pronounceableWord->generate();

        if (0 === $this->find('count', array('conditions' => array('Character.name' => $generatedName)))) {
            $this->create();
            $isSaved = $this->save(array(
                'name' => $generatedName,
                'resource_kept' => DEFAULT_RESOURCE_KEPT,
                'resource_spent' => 0,
                'attack_modifier' => 0,
                'defense_modifier' => 0,
                'resource_modifier' => 0,
            ));
            if (false !== $isSaved) {
                $hasGenerated = true;
            }
        }

        return $hasGenerated;
    }

    /**
     * Counts the number of characters created in the last 24 hours.
     *
     * @return integer The number of characters.
     */
    public function countGeneratedForLastDay() {
        $lastDay = strtotime('-1 day');

        $generated = $this->find('count', array('conditions' => array(
            'Character.created >=' => date('Y-m-d H:i:s', $lastDay),
        )));

        return $generated;
    }

    /**
     * Removes the dead characters.
     */
    public function removeDeads() {
        $this->deleteAll('UNIX_TIMESTAMP(NOW()) >= UNIX_TIMESTAMP(Character.created) + Character.resource_kept');
    }
}
